package com.project.poetry.common.entity;

import com.project.poetry.common.constant.ConstantEnum;
import com.project.poetry.common.constant.ExceptionCode;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * 接口通用返回体
 * @author mengxj
 */
@Data
@NoArgsConstructor
public class R<T> {

    @ApiModelProperty(value = "状态码", required = true)
    private Integer code;

    @ApiModelProperty("承载数据")
    private T data;

    @ApiModelProperty(value = "返回消息", required = true)
    private String message;

    public R(ConstantEnum constant){
        this(constant, null);
    }

    public R(ConstantEnum constant, T t){
        this.code = constant.getCode();
        this.data = t;
        String msg = constant.getMessage();
        this.message = this.code == 200
                ? msg
                : String.format(" %s   %s", ExceptionCode.getValue(this.code), msg);
    }

    public static <T> R<T> success() {
        return success(null);
    }

    public static <T> R<T> success(T t) {
        return new R<>(ConstantEnum.SUCCESS, t);
    }

    public static <T> R<T> fail() {
        return new R<>(ConstantEnum.FAILED);
    }

    public static <T> R<T> fail(String message) {
        return new R<>(ConstantEnum.errMessage(message));
    }

    public static <T> R<T> fail(ConstantEnum constantEnum) {
        return new R<>(constantEnum);
    }
}